package com.bwie.util;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.UUID;

public class FileUploadUtil {

	//上传
	public static String  load(HttpSession session, MultipartFile file, String toPath) {
		// 获取原始文件名称
		String originalFilename = file.getOriginalFilename();
		// 获取后缀名前.的位置
		int indexOf = originalFilename.lastIndexOf(".");
		// 截取从. 开始一直到最后  获取后缀
		String houzhui = originalFilename.substring(indexOf);
		// 生成唯一字符串（目的是保证上传路径下 文件名不重复）
		String string = UUID.randomUUID().toString();
		// 获取 请求路径
		String realPath = session.getServletContext().getRealPath("/"+toPath);
		// 文件的完整路径
		String path=realPath+File.separator+string+houzhui;
		
		// 上传文件
		File file2 = new File(path);
		try {
			file.transferTo(file2); // 上传核心方法
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return toPath+"/"+string+houzhui;
	}

	// 多文件上传
	public static String[] loads(HttpSession session, MultipartFile[] file, String toPath){
		String[] strings=new String[file.length];
		for (int i=0;i<file.length;i++) {
			if(file[i].getOriginalFilename().length()>0){
				String load = load(session, file[i], toPath);
				strings[i]=load;
			}
		}
		return strings;
	}

	// 下载
	public static  void down(String fileName,String toPath,HttpServletResponse response,HttpServletRequest request) {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("multipart/form-data");
		// 设置下在的头文件  格式
		response.setHeader("Content-Disposition", "attachment;fileName="
				+ fileName);
		// 获取文件的 绝对路径
		String realPath = request.getSession().getServletContext().getRealPath("/"+toPath+"/");
		realPath=realPath+File.separator+fileName;
		try {
			FileInputStream fis=new FileInputStream(realPath);
			OutputStream outputStream = response.getOutputStream();
			int read=0;
			while((read=fis.read())!=-1) {
				outputStream.write(read);
			}
			
			close(fis,outputStream);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	// 关流
	public  static void  close(InputStream is,OutputStream os) {
		try {
			if(is!=null) {
				is.close();
			}
			if(os!=null) {
				os.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
